package com.ruoyi.web.controller.net;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementPortMtnEvth;
import com.ruoyi.net.service.IElementPortMtnEvthService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-接口-mtnevth接口Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-接口-mtnevth接口(VETH)")
@RestController
@RequestMapping("/element/port/mtn/evth")
public class ElementPortMtnEvthController extends BaseController {
    @Autowired
    private IElementPortMtnEvthService elementPortMtnEvthService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 读取网元-接口-mtnevth接口列表
     */
    @ApiOperation(value = "读取网元-接口-mtnevth接口列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:evth:list')")
    @GetMapping("/read")
    public TableDataInfo read(ElementPortMtnEvth elementPortMtnEvth) {
        List<ElementPortMtnEvth> elementPortMtnEvths = new ArrayList<>();
        StringBuilder xml = new StringBuilder();
        xml.append(
                "<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                        "        <type>ETH-VIR</type>" +
                        "        <enabled>enable</enabled>" +
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
        NetElement netElement = netElementService.getCacheObject(elementPortMtnEvth.getElementId());
        if (sysConfigService.selectDebugEnabled()) {
            deviceManager.getDevice(netElement.getIp());
            String rpcReply = deviceManager.getConfig(xml.toString());

            // 解析xml
            NodeList list = findNetConfXmlNodes(rpcReply, "//interfaces/interface");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementPortMtnEvth entity = new ElementPortMtnEvth();
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    entity.setTerminalName(getXmlLabelValue(node, "name"));
//                    entity.setTerminalEnable(getXmlLabelValue(node, "enabled"));
//                    entity.setPortDesc(getXmlLabelValue(node, "description"));
                    Node ethOption = getXmlLabelNode(node, "eth-option");
                    entity.setMac(getXmlLabelValue(ethOption, "mac-address"));
                    Node flexevethifInterface = getXmlLabelNode(node, "flexevethif-interface");
                    entity.setTerminalMode(getXmlLabelValue(node, "transport-layer"));
                    entity.setMbps(getXmlLabelValue(node, "bandwidth"));
                    Node ipNode = getXmlLabelNode(node, "ip");
                    entity.setMaxFrameLen(getXmlLabelValue(ipNode, "ipv4-mtu"));
                    Node ipv4AddressListNode = getXmlLabelNode(ipNode, "ipv4-address-list");
                    if (ipv4AddressListNode != null) {
                        String ip = getXmlLabelValue(ipv4AddressListNode, "ipv4-address");
                        entity.setIp(StringUtils.isNotEmpty(ip) ? ip.split("/")[0] : "");
                        entity.setMask(StringUtils.isNotEmpty(ip) ? ip.split("/")[1] : "");
                        entity.setIpForm(getXmlLabelValue(ipv4AddressListNode, "secondry-use"));
                    }
                    entity.setStatus("1"); // 从设备读取到的配置，设置状态为激活

                    elementPortMtnEvths.add(entity);
                }
            }
        }
        startPage();
        return getDIYPageTable(elementPortMtnEvths);
    }

    /**
     * 查询网元-接口-mtnevth接口列表
     */
    @ApiOperation(value = "查询网元-接口-mtnevth接口列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:evth:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementPortMtnEvth elementPortMtnEvth) {
        startPage();
        List<ElementPortMtnEvth> list = elementPortMtnEvthService.selectElementPortMtnEvthList(elementPortMtnEvth);
        return getDataTable(list);
    }

    /**
     * 导出网元-接口-mtnevth接口列表
     */
    @ApiOperation(value = "导出网元-接口-mtnevth接口列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:evth:export')")
    @Log(title = "网元-接口-mtnevth接口", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementPortMtnEvth elementPortMtnEvth) {
        List<ElementPortMtnEvth> list = elementPortMtnEvthService.selectElementPortMtnEvthList(elementPortMtnEvth);
        ExcelUtil<ElementPortMtnEvth> util = new ExcelUtil<ElementPortMtnEvth>(ElementPortMtnEvth.class);
        util.exportExcel(response, list, "网元-接口-mtnevth接口数据");
    }

    /**
     * 获取网元-接口-mtnevth接口详细信息
     */
    @ApiOperation(value = "获取网元-接口-mtnevth接口详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:evth:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementPortMtnEvthService.selectElementPortMtnEvthById(id));
    }

    /**
     * 新增网元-接口-mtnevth接口
     */
    @ApiOperation(value = "新增网元-接口-mtnevth接口", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:evth:add')")
    @Log(title = "网元-接口-mtnevth接口", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementPortMtnEvth elementPortMtnEvth) {
        return toAjax(elementPortMtnEvthService.insertElementPortMtnEvth(elementPortMtnEvth));
    }

    /**
     * 修改网元-接口-mtnevth接口
     */
    @ApiOperation(value = "修改网元-接口-mtnevth接口", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:evth:edit')")
    @Log(title = "网元-接口-mtnevth接口", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementPortMtnEvth elementPortMtnEvth) {
        return toAjax(elementPortMtnEvthService.updateElementPortMtnEvth(elementPortMtnEvth));
    }

    /**
     * 删除网元-接口-mtnevth接口
     */
    @ApiOperation(value = "删除网元-接口-mtnevth接口", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:evth:remove')")
    @Log(title = "网元-接口-mtnevth接口", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementPortMtnEvthService.deleteElementPortMtnEvthByIds(ids));
    }

    /**
     * 激活设备
     *
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @GetMapping(value = "/activate/{id}")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementPortMtnEvth elementPortMtnEvth = elementPortMtnEvthService.selectElementPortMtnEvthById(id);
        elementPortMtnEvth.setStatus("1");
        if (sendXml(elementPortMtnEvth)) {
            return toAjax(elementPortMtnEvthService.updateElementPortMtnEvth(elementPortMtnEvth));
        } else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     *
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementPortMtnEvth elementPortMtnEvth = elementPortMtnEvthService.selectElementPortMtnEvthById(id);
        elementPortMtnEvth.setStatus("0");
        if (sendXml(elementPortMtnEvth)) {
            return toAjax(elementPortMtnEvthService.updateElementPortMtnEvth(elementPortMtnEvth));
        } else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementPortMtnEvth entity) {
        // TODO: 2024/12/21 待与设备联调
        boolean isSend = true;
        if (sysConfigService.selectDebugEnabled()) {
            NetElement netElement = netElementService.getCacheObject(entity.getElementId());
            deviceManager.getDevice(netElement.getIp());
            StringBuilder xml = new StringBuilder();
          if (("1").equals(entity.getStatus())) {
              xml.append("    <if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                      "        <interfaces>" +
                      "          <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                      "            <name>flexe-tunnel"+entity.getTerminalName().split("mtnveth")[1]+"</name>" +//mtn veth口的端口名称
                      "            <type>FLEXE-TUNNEL</type>" +
                      "            <ip xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-l2l3common\">" +
                      "              <ipv4-address-list>" +
                      "                <ipv4-address>"+entity.getIp()+"/"+entity.getMask()+"</ipv4-address>" +//取mtn veth口的ip  掩码
                      "                <secondry-use>mast</secondry-use>" +
                      "              </ipv4-address-list>" +
                      "            </ip>" +
                      "          </interface>" +
                      "        </interfaces>" +
                      "      </if>");
          }else{
              xml.append(" <if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                      "        <interfaces>" +
                      "          <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" nc:operation=\"remove\">" +
                      "            <name>flexe-tunnel"+entity.getTerminalName().split("mtnveth")[1]+"</name>" +
                      "            <type>FLEXE-TUNNEL</type>" +
                      "          </interface>" +
                      "        </interfaces>" +
                      "      </if>");

          }

            
            System.out.println(xml);
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }
        return isSend;
    }
}